package com.unionfetch.content_home.ui.account

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.unionfetch.content_home.R
import com.unionfetch.content_home.bean.AccountType
import com.unionfetch.content_home.bean.request.AddDemoAccountRequest
import com.unionfetch.content_home.contract.AccountContract
import com.unionfetch.content_home.presenter.AccountPresenter
import com.unionfetch.content_home.ui.dialog.CustomSelectDialog
import com.unionfetch.content_home.ui.dialog.CustomTipDialog
import com.unionfetch.content_home.ui.fragment.HomeFragment
import com.unionftech.common.R.color
import com.unionftech.common.R.string
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.bean.Platform
import com.unionftech.common.common.bean.TradePlatform
import com.unionftech.common.common.contract.CommonContract
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.common.presenter.CommonPresenter
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.formatAsMoney

class AddDemoTradeAccountActivity : BaseMvpActivity(), CommonContract.IPlatformView,
    AccountContract.IAddDemoAccountView {
    private val mBtnConfirm by lazy { findViewById<Button>(R.id.btn_confirm) }
    private val mEtDemoLever by lazy { findViewById<TextView>(R.id.et_demo_lever) }
    private val mTvDemoLeverTitle by lazy { findViewById<TextView>(R.id.tv_demo_lever_title) }
    private val mEtDepositAmount by lazy { findViewById<TextView>(R.id.et_deposit_amount) }
    private val mTvDepositAmountTitle by lazy { findViewById<TextView>(R.id.tv_deposit_amount_title) }
    private val mEtAccountCurrency by lazy { findViewById<TextView>(R.id.et_account_currency) }
    private val mTvAccountCurrencyTitle by lazy { findViewById<TextView>(R.id.tv_account_currency_title) }
    private val mEtAccountType by lazy { findViewById<TextView>(R.id.et_account_type) }
    private val mTvAccountTypeTitle by lazy { findViewById<TextView>(R.id.tv_account_type_title) }
    private val mEtTradePlatform by lazy { findViewById<TextView>(R.id.et_trade_platform) }
    private val mTvTradePlatformTitle by lazy { findViewById<TextView>(R.id.tv_trade_platform_title) }
    private val mTvDemoCreateTip by lazy { findViewById<TextView>(R.id.tv_demo_create_tip) }
    private var mIsShowSelectDialog: Boolean = false

    @InjectPresenter
    private lateinit var mCommonPresenter: CommonPresenter

    @InjectPresenter
    private lateinit var mAccountPresenter: AccountPresenter

    //平台类型
    private val mTradePlatformList = mutableListOf<TradePlatform>()
    private var mTradePlatformIndex = -1

    //账户类型选项
    private val mAccountTypeList: List<AccountType> = AccountType.entries
    private var mAccountTypeIndex = -1

    //币种
    private val mCurrencyList = listOf("USD", "GBP", "EUR")
    private var mCurrencyIndex = -1

    //入金额选项
    private val mDepositAmountList = listOf(3000, 5000, 25000, 50000, 100000, 500000, 1000000)
    private var mDepositAmountIndex = -1

    //杠杆选项
    private val mDemoLeverList = listOf(1, 50, 100, 200, 300, 400, 500)
    private var mDemoLeverIndex = -1

    companion object {
        private const val TAG = "AddLiveTradeAccountActivity"

        @JvmStatic
        fun startThis(context: Context) {
            Intent(context, AddDemoTradeAccountActivity::class.java).apply {
                if (context !is Activity) {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                context.startActivity(this)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun initLayout() = R.layout.activity_add_demo_trade_account

    override fun initLanguageText() {
        super.initLanguageText()
        mTvDemoCreateTip.text = DynamicResourceManager.getString(string.add_demo_account_attention)

        mTvTradePlatformTitle.text = DynamicResourceManager.getString(string.trading_platform)
        mEtTradePlatform.hint = DynamicResourceManager.getString(string.please_select)
        mTvAccountTypeTitle.text = DynamicResourceManager.getString(string.trading_account_type)
        mEtAccountType.hint = DynamicResourceManager.getString(string.please_select)
        mTvAccountCurrencyTitle.text = DynamicResourceManager.getString(string.account_currency)
        mEtAccountCurrency.hint = DynamicResourceManager.getString(string.please_select)
        mTvDepositAmountTitle.text = DynamicResourceManager.getString(string.deposit_amount)
        mEtDepositAmount.hint = DynamicResourceManager.getString(string.please_select)
        mTvDemoLeverTitle.text = DynamicResourceManager.getString(string.lever)
        mEtDemoLever.hint = DynamicResourceManager.getString(string.please_select)
        mBtnConfirm.text = DynamicResourceManager.getString(string.confirm)
    }

    override fun setListener() {
        super.setListener()
        mEtTradePlatform.setOnClickListener(this)
        mEtAccountType.setOnClickListener(this)
        mEtAccountCurrency.setOnClickListener(this)
        mEtDepositAmount.setOnClickListener(this)
        mEtDemoLever.setOnClickListener(this)
        mBtnConfirm.setOnClickListener(this)
    }

    override fun setView() {
        super.setView()
        hideCenterTitle()
        initTitleBar()
        loadData()
        mBtnConfirm.isEnabled = false
    }

    private fun initTitleBar() {
        setBackText(
            DynamicResourceManager.getString(string.add_demo_account), mContext.resources.getColor(
                color.color_1C1D21
            )
        )
    }

    override fun loadData() {
        super.loadData()
        queryPlatform(false)
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.et_trade_platform -> {
                //选择交易平台
                queryPlatform(true)
            }

            R.id.et_account_type -> {
                //选择账户类型
                showAccountTypeDialog()
            }

            R.id.et_account_currency -> {
                //选择账户币种
                showCurrencyDialog()
            }

            R.id.et_deposit_amount -> {
                //选择入金金额
                showDepositAmountDialog()
            }

            R.id.et_demo_lever -> {
                //选择杠杆
                showDemoLever()
            }

            R.id.btn_confirm -> {
                //提交
                submit()
            }
        }
    }

    private fun queryPlatform(showDialog: Boolean) {
        mIsShowSelectDialog = showDialog
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mCommonPresenter.querySystemDemoPlatform(userToken)
    }

    private fun setButtonEnable() {
        mBtnConfirm.isEnabled = checkButtonEnable()
    }

    private fun checkButtonEnable(): Boolean {
        if (mTradePlatformIndex == -1) {
            return false
        }
        if (mAccountTypeIndex == -1) {
            return false
        }
        if (mCurrencyIndex == -1) {
            return false
        }
        if (mDepositAmountIndex == -1) {
            return false
        }
        if (mDemoLeverIndex == -1) {
            return false
        }
        return true
    }

    private fun submit() {
        getRequest()?.also {
            val userToken = GlobalInfoManager.getInstance().getUserToken()
            mAccountPresenter.createDemoAccount(userToken, it)
        }
    }

    private fun getRequest(): AddDemoAccountRequest? {
        if (!checkButtonEnable()) {
            return null
        }
        val request = AddDemoAccountRequest().apply {
            //平台
            mTradePlatformList.getOrNull(mTradePlatformIndex)?.also { result ->
                platform = result.platform
            }
            //账户类型
            mAccountTypeList.getOrNull(mAccountTypeIndex)?.also {
                accountType = it.accountType
            }
            //币种
            mCurrencyList.getOrNull(mCurrencyIndex)?.also {
                currency = it
            }
            //入金金额
            mDepositAmountList.getOrNull(mDepositAmountIndex)?.also {
                chargeAmount = it
            }
            //杠杆
            mDemoLeverList.getOrNull(mDemoLeverIndex)?.also {
                leverage = it
            }

        }
        return request
    }

    private fun showCurrencyDialog() {
        val dialog = CustomSelectDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.account_currency))
            .setSelectIndex(mCurrencyIndex).setItemData(mCurrencyList).setCallBack { index ->
                mCurrencyList.getOrNull(index)?.also { result ->
                    mEtAccountCurrency.text = result
                    mCurrencyIndex = index
                    setButtonEnable()
                }
            }.show()
    }

    private fun showAccountTypeDialog() {
        val list = mutableListOf<String>()
        for (accountType in mAccountTypeList) {
            list.add(DynamicResourceManager.getString(accountType.stringId))
        }
        val dialog = CustomSelectDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.trading_account_type))
            .setSelectIndex(mAccountTypeIndex).setItemData(list).setCallBack { index ->
                list.getOrNull(index)?.also { result ->
                    mEtAccountType.text = result
                    mAccountTypeIndex = index
                    setButtonEnable()
                }
            }.show()
    }

    private fun showDepositAmountDialog() {
        val list = mutableListOf<String>()
        for (amount in mDepositAmountList) {
            list.add(amount.formatAsMoney())
        }
        val dialog = CustomSelectDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.deposit_amount))
            .setSelectIndex(mDepositAmountIndex).setItemData(list).setCallBack { index ->
                mDepositAmountList.getOrNull(index)?.also { result ->
                    mEtDepositAmount.text = result.formatAsMoney()
                    mDepositAmountIndex = index
                    setButtonEnable()
                }
            }.show()
    }

    private fun showDemoLever() {
        val list = mutableListOf<String>()
        for (lever in mDemoLeverList) {
            list.add("1:${lever}")
        }
        val dialog = CustomSelectDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.lever))
            .setSelectIndex(mDemoLeverIndex).setItemData(list).setCallBack { index ->
                list.getOrNull(index)?.also { result ->
                    mEtDemoLever.text = result
                    mDemoLeverIndex = index
                    setButtonEnable()
                }
            }.show()
    }


    private fun showTradePlatformDialog() {
        if (mTradePlatformList.isEmpty()) {
            return
        }
        val list = mutableListOf<String>()
        for (platform in mTradePlatformList) {
            if (platform.platform == Platform.MT4.platform) {
                list.add(Platform.MT4.desc)
            } else if (platform.platform == Platform.MT5.platform) {
                list.add(Platform.MT5.desc)
            }
        }
        val dialog = CustomSelectDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.trading_platform))
            .setSelectIndex(mTradePlatformIndex).setItemData(list).setCallBack { index ->
                list.getOrNull(index)?.also { result ->
                    mEtTradePlatform.text = result
                    mTradePlatformIndex = index
                    setButtonEnable()
                }
            }.show()
    }

    override fun backPressed(): Boolean {
        showLeaveDialog()
        return true
    }

    /**
     * 屏蔽物理返回键
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    private fun showLeaveDialog() {
        val dialog = CustomTipDialog(mContext)
        dialog.setTopRes(R.drawable.ic_circle_warning)
            .setTitle(DynamicResourceManager.getString(mContext, string.confirm_leave))
            .setCancelText(
                DynamicResourceManager.getString(
                    mContext, string.cancel
                )
            ).setConfirmText(
                DynamicResourceManager.getString(
                    mContext, string.confirm
                )
            ).setCallBack { confirm ->
                if (confirm) {
                    finish()
                }
                dialog.dismiss()
            }.show()
    }

    override fun handlePlatformView(response: ResponseResult<List<TradePlatform>>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                mTradePlatformList.clear()
                mTradePlatformList.addAll(it)
                if (mTradePlatformList.isEmpty()) {
                    mTradePlatformIndex = -1
                    mEtTradePlatform.text =
                        DynamicResourceManager.getString(string.no_platform_select)
                    return
                }
                if (mIsShowSelectDialog) {
                    mIsShowSelectDialog = false
                    showTradePlatformDialog()
                }
            }
        } else {
            LogUtils.d(TAG, "handlePlatformView error->$response")
            response.toast()
        }
    }

    override fun handleAddDemoAccount(response: ResponseResult<Any?>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            showApplySuccessDialog()
            GlobalInfoManager.getInstance()
                .notify(DemoAccountListFragment::class.java, GlobalInfoManager.UPDATE_DEMO_LIST)
            GlobalInfoManager.getInstance()
                .notify(HomeFragment::class.java, GlobalInfoManager.UPDATE_DEMO_LIST)
        } else {
            LogUtils.d(TAG, "handleAddDemoAccount error->$response")
            response.toast()
        }
    }

    private fun showApplySuccessDialog() {
        val tipDialog = CustomTipDialog(mContext)
        tipDialog.setTopRes(R.drawable.ic_circle_success)
            .setTitle(DynamicResourceManager.getString(string.application_successful))
            .setMessage(DynamicResourceManager.getString(string.add_demo_account_success))
            .setConfirmText(DynamicResourceManager.getString(string.close)).setCallBack {
                finish()
            }.show()
    }
}